#import "ViewController.h"
#include "../src/native-lib.h"

@implementation ViewController {
    BOOL _success;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        int port = [self extractPortFromArguments:[[NSProcessInfo processInfo] arguments]];
        if (port == 0) {
            port = 50051;
        }
        _success = StartGRPCServer(port);
    }
    return self;
}

- (int)extractPortFromArguments:(NSArray<NSString *> *)arguments {
    for (NSString *arg in arguments) {
        NSArray<NSString *> *components = [arg componentsSeparatedByString:@"="];
        if (components.count == 2 && [components[0] isEqualToString:@"port"]) {
            return [components[1] intValue];
        }
    }
    return 0;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = UIColor.whiteColor;

    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 21)];
    label.translatesAutoresizingMaskIntoConstraints = NO;
    label.textAlignment = NSTextAlignmentCenter;

    if (!_success) {
        label.text = @"Failed to start server";
    } else {
        int port = GetGRPCServerPort();
        label.text = [NSString stringWithFormat:@"Server started with port %d", port];
    }

    [self.view addSubview:label];

    [NSLayoutConstraint activateConstraints:@[
        [label.centerXAnchor constraintEqualToAnchor:self.view.centerXAnchor],
        [label.centerYAnchor constraintEqualToAnchor:self.view.centerYAnchor]
    ]];
}

- (void)dealloc {
    StopGRPCServer();
}

@end
